package com.caiheng.api.controller.estate;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.asset.EstateAsset;
import com.caiheng.api.entity.asset.EstateAssetBorrowRecord;
import com.caiheng.api.entity.asset.EstateAssetCheckRecord;
import com.caiheng.api.entity.asset.EstateAssetCheckRecordImg;
import com.caiheng.api.entity.estate.*;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.asset.IEstateAssetBorrowRecordService;
import com.caiheng.api.service.asset.IEstateAssetCheckRecordImgService;
import com.caiheng.api.service.asset.IEstateAssetCheckRecordService;
import com.caiheng.api.service.asset.IEstateAssetService;
import com.caiheng.api.service.estate.*;
import com.caiheng.api.service.platfom.WxTemplateService;
import com.caiheng.api.service.sys.SysUserService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.*;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  资产管理接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/estate/asset")//url:模块/资源/{}/细分
public class EstateAssetController extends BaseController {
    @Resource
    private UserService userService;
    @Resource
    private IEstateAssetService estateAssetService;
    @Resource
    private IEstateAssetBorrowRecordService assetBorrowRecordService;
    @Resource
    private IEstateAssetCheckRecordService assetCheckRecordService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private EstateService estateService;
    @Resource
    private PropertyService propertyService;
    @Resource
    private EstateUserService estateUserService;
    @Resource
    private IEstateAssetCheckRecordImgService assetCheckRecordImgService;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址


    @Value("${web.imgPrefix}")
    private String imgPrefix;//图片地址

    /**
     * 资产列表（固定资产，带有巡查次数的）
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String, Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/asset/list 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int asset_type = jsonRequest.containsKey("asset_type") ? jsonRequest.getInt("asset_type") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 0;
            int checkState = jsonRequest.containsKey("checkState") ? jsonRequest.getInt("checkState") : 0;//0 - 未完成的  1 - 已完成的
            String searchValue = jsonRequest.containsKey("searchValue") ? jsonRequest.getStr("searchValue") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无上报权限"),true,true);
            }

            EstateUser estateUser = estateUserService.getEstateByManagerUser(user_id);
            if(estateUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }
            int offset = (pageIndex - 1) * pageSize;
            List<EstateAsset> assetList = new ArrayList<>();
            if(asset_type == 0){//固定资产
                Map<String, Object> mapParam = new HashMap<>();
                mapParam.put("estateId", estateUser.getEstateId());
                mapParam.put("checkState", checkState);
                assetList = estateAssetService.getAssetListByTime(mapParam, offset, pageSize);
            }else{//移动资产
                QueryWrapper<EstateAsset> qw = new QueryWrapper<>();
                qw.eq("property_id", sysUser.getPropertyId());
                qw.eq("asset_type", 1);//移动资产
                if(StrUtil.isNotEmpty(searchValue)){
                    qw.like("asset_name", searchValue);
                }
                assetList = estateAssetService.getPageEntityList(qw, pageIndex, pageSize);
                for (EstateAsset asset : assetList){
                    QueryWrapper<EstateAssetBorrowRecord> qwBorrow = new QueryWrapper<>();
                    qwBorrow.eq("asset_id", asset.getId());
                    qwBorrow.last("limit 1");
                    qwBorrow.orderByDesc("create_time");
                    EstateAssetBorrowRecord borrowRecord = assetBorrowRecordService.getOne(qwBorrow);
                    if(borrowRecord!= null){
                        Estate estate = estateService.findById(borrowRecord.getEstateId());
                        if(estate!= null){
                            borrowRecord.setEstateName(estate.getEstateName());
                        }
                        asset.setBorrowRecord(borrowRecord);
                    }
                }
            }
            for (EstateAsset asset : assetList){
                Property property = propertyService.findById(asset.getPropertyId());
                if(property != null){
                    asset.setPropertyName(property.getPropertyName());
                }
            }
            map.put("assetList", assetList);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功", assetList.size(), map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 资产详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String, Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/asset/stock/taking 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int asset_id = jsonRequest.containsKey("asset_id") ? jsonRequest.getInt("asset_id") : 0;
            //操作类型 从哪操作的   借用还是盘点 0 - 借用 1 - 盘点
            int op_type = jsonRequest.containsKey("op_type") ? jsonRequest.getInt("op_type") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无上报权限"),true,true);
            }

            map.put("is_estate_user", 1);
            EstateUser estateUser = estateUserService.getEstateByManagerUser(user_id);
            if(estateUser == null){
                map.put("is_estate_user", 0);
            }

            EstateAsset asset = estateAssetService.findById(asset_id);
            if(asset == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该资产不存在"),true,true);
            }

            Estate estate = estateService.findById(asset.getEstateId());
            if(estate != null){
                asset.setEstateName(estate.getEstateName());
            }

            Property property = propertyService.findById(asset.getPropertyId());
            if(property != null){
                asset.setPropertyName(property.getPropertyName());
            }

            map.put("asset", asset);

            if(op_type == 0){// 借用
                QueryWrapper<EstateAssetBorrowRecord> qw = new QueryWrapper<>();
                qw.eq("asset_id", asset_id);
                qw.orderByDesc("create_time");
                qw.last("limit 1");
                EstateAssetBorrowRecord borrowRecord = assetBorrowRecordService.getOne(qw);
                map.put("borrowRecord", borrowRecord);

            }else{//盘点
                QueryWrapper<EstateAssetCheckRecord> qw = new QueryWrapper<>();
                qw.eq("asset_id", asset_id);
                qw.orderByDesc("create_time");
                qw.last("limit 1");
                EstateAssetCheckRecord lastCheck = assetCheckRecordService.getOne(qw);
                map.put("lastCheck", lastCheck);
            }


            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功", map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 资产盘点上报操作
     * @param
     * @throws Exception
     */
    @PostMapping(value="/stock/taking")
    public JSONObject stocktaking(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/asset/stock/taking 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int asset_id = jsonRequest.containsKey("asset_id") ? jsonRequest.getInt("asset_id") : 0;
            int check_state = jsonRequest.containsKey("check_state") ? jsonRequest.getInt("check_state") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无上报权限"),true,true);
            }


            EstateUser estateUser = estateUserService.getEstateByManagerUser(user_id);
            if(estateUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无上报权限"),true,true);
            }

            EstateAsset asset = estateAssetService.findById(asset_id);
            if(asset == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该资产不存在"),true,true);
            }

            if(estateUser.getEstateId().intValue() != asset.getEstateId().intValue()){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无上报权限"),true,true);
            }


            EstateAssetCheckRecord checkRecord = new EstateAssetCheckRecord();
            checkRecord.setPropertyId(asset.getPropertyId());
            checkRecord.setEstateId(asset.getEstateId());
            checkRecord.setCheckState(check_state);
            checkRecord.setCreateTime(new Date());
            checkRecord.setWxUserId(user_id);
            checkRecord.setSysUserId(sysUser.getUserId());
            checkRecord.setRealName(sysUser.getNickName());
            checkRecord.setNickName(user.getNickName());
            checkRecord.setPhoneNum(sysUser.getPhoneNum());
            checkRecord.setAssetId(asset_id);

            int ret = assetCheckRecordService.stockTaking(asset, checkRecord);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"盘点成功", checkRecord.getId()),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"盘点失败，请重试"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 盘点固定资产记录
     * @param
     * @throws Exception
     */
    @PostMapping(value="/stock/taking/record")
    public JSONObject stockTakingRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String, Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/asset/stock/taking/record 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int asset_id = jsonRequest.containsKey("asset_id") ? jsonRequest.getInt("asset_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            QueryWrapper<EstateAssetCheckRecord> qw = new QueryWrapper<>();
            qw.eq("asset_id", asset_id);
            qw.orderByDesc("create_time");
            List<EstateAssetCheckRecord> list = assetCheckRecordService.getPageEntityList(qw, pageIndex, pageSize);
            for (EstateAssetCheckRecord record : list){
                EstateAsset asset = estateAssetService.findById(record.getAssetId());
                if(asset != null){
                    record.setAssetName(asset.getAssetName());
                }
                Property property = propertyService.findById(record.getPropertyId());
                if(property != null){
                    record.setPropertyName(property.getPropertyName());
                }

                Estate estate = estateService.findById(record.getEstateId());
                if(estate != null){
                    record.setEstateName(estate.getEstateName());
                }

                QueryWrapper<EstateAssetCheckRecordImg> qwImg = new QueryWrapper<>();
                List<EstateAssetCheckRecordImg> imgList = assetCheckRecordImgService.list(qwImg);
                for (EstateAssetCheckRecordImg img : imgList){
                    img.setImgUrl(imgPrefix + img.getImgUrl());
                }
                record.setImgList(imgList);
            }
            map.put("records", list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功", list.size(), map),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 我借用的移动资产列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/borrow/list")
    public JSONObject borrowList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String, Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/asset/stock/taking 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            QueryWrapper<EstateAssetBorrowRecord> qw = new QueryWrapper<>();
            qw.eq("wx_user_id", user_id);
            qw.orderByDesc("create_time");
            List<EstateAssetBorrowRecord> list = assetBorrowRecordService.getPageEntityList(qw, pageIndex, pageSize);
            for (EstateAssetBorrowRecord record : list){
                EstateAsset asset = estateAssetService.findById(record.getAssetId());
                if(asset != null){
                    record.setAssetName(asset.getAssetName());
                    record.setDeviceNum(asset.getDeviceNum());
                }
                record.setRebackImg(imgPrefix + record.getRebackImg());
            }
            map.put("recordList", list);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功",list.size(),  map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 借用移动资产
     * @param
     * @throws Exception
     */
    @PostMapping(value="/borrow")
    public JSONObject borrow(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/asset/stock/taking 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int asset_id = jsonRequest.containsKey("asset_id") ? jsonRequest.getInt("asset_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            EstateAsset asset = estateAssetService.findById(asset_id);
            if(asset == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该资产不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无上报权限"),true,true);
            }

            if(asset.getAssetType() == 0){
                EstateUser estateUser = estateUserService.getEstateByManagerUser(user_id);
                if(estateUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无上报权限"),true,true);
                }

                if(estateUser.getEstateId().intValue() != asset.getEstateId().intValue()){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无上报权限"),true,true);
                }
            }else{
                if(sysUser.getPropertyId().intValue() != asset.getPropertyId().intValue()){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无上报权限"),true,true);
                }
            }

            //资产状态 0-正常 1-维修 2-报废 3-借出
            if(asset.getState() == 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备维修中..."),true,true);
            } else if(asset.getState() == 2){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备已报废"),true,true);
            }


            QueryWrapper<EstateAssetBorrowRecord> qw = new QueryWrapper<>();
            qw.eq("asset_id", asset.getId());
            qw.eq("wx_user_id", user_id);
            qw.eq("state", 0);
            qw.orderByDesc("create_time");
            qw.last("limit 1");
            EstateAssetBorrowRecord lastBorrowRecord = assetBorrowRecordService.getOne(qw);
            if(lastBorrowRecord!= null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该资产您已借出，无需重复借用"),true,true);
            }


            int ret = assetBorrowRecordService.borrow(user,sysUser, asset);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"借用成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 借用移动资产记录
     * @param
     * @throws Exception
     */
    @PostMapping(value="/borrow/record")
    public JSONObject borrowRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String, Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/asset/stock/taking 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int asset_id = jsonRequest.containsKey("asset_id") ? jsonRequest.getInt("asset_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            QueryWrapper<EstateAssetBorrowRecord> qw = new QueryWrapper<>();
            qw.eq("asset_id", asset_id);
            qw.orderByDesc("create_time");
            List<EstateAssetBorrowRecord> list = assetBorrowRecordService.getPageEntityList(qw, pageIndex, pageSize);
            for (EstateAssetBorrowRecord record : list){
                EstateAsset asset = estateAssetService.findById(record.getAssetId());
                if(asset != null){
                    record.setAssetName(asset.getAssetName());
                }
                Property property = propertyService.findById(record.getPropertyId());
                if(property != null){
                    record.setPropertyName(property.getPropertyName());
                }

                Estate estate = estateService.findById(record.getEstateId());
                if(estate != null){
                    record.setEstateName(estate.getEstateName());
                }

            }
            map.put("records", list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功", list.size(), map),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 借用移动资产记录详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/borrow/record/detail")
    public JSONObject borrowRecordDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String, Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/asset/stock/taking 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int borrow_record_id = jsonRequest.containsKey("borrow_record_id") ? jsonRequest.getInt("borrow_record_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            EstateAssetBorrowRecord borrowRecord = assetBorrowRecordService.findById(borrow_record_id);
            if(borrowRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"借用信息不存在"),true,true);
            }


            EstateAsset asset = estateAssetService.findById(borrowRecord.getAssetId());
            if(asset == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该资产不存在"),true,true);
            }
            map.put("asset", asset);

            map.put("borrowInfo", borrowRecord);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功", map),true,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }




    /**
     * 归还移动资产
     * @param
     * @throws Exception
     */
    @PostMapping(value="/reback")
    public JSONObject reback(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/asset/stock/taking 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int asset_id = jsonRequest.containsKey("asset_id") ? jsonRequest.getInt("asset_id") : 0;
            int borrow_record_id = jsonRequest.containsKey("borrow_record_id") ? jsonRequest.getInt("borrow_record_id") : 0;
            double lng = jsonRequest.containsKey("lng") ? jsonRequest.getDouble("lng") : 0d;
            double lat  = jsonRequest.containsKey("lat") ? jsonRequest.getDouble("lat") : 0d;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            EstateAsset asset = estateAssetService.findById(asset_id);
            if(asset == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该资产不存在"),true,true);
            }

            EstateAssetBorrowRecord borrowRecord = assetBorrowRecordService.findById(borrow_record_id);
            if(borrowRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"借用信息不存在"),true,true);
            }

            if(borrowRecord.getWxUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该借用信息不属于你"),true,true);
            }

            borrowRecord.setState(1);
            borrowRecord.setRebackTime(new Date());
            borrowRecord.setRebackLng(new BigDecimal(lng));
            borrowRecord.setRebackLat(new BigDecimal(lat));
            int ret = assetBorrowRecordService.reback(asset, borrowRecord);

            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"归还成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"归还失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }



    /**
     *  资产归还上传图片
     * @param
     * @throws Exception
     */
    @PostMapping(value="/reback/uploadImg")
    public JSONObject rebackUploadImg(@RequestParam("record_id") int record_id,HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("record_id==" + record_id);

            EstateAssetBorrowRecord borrowRecord = assetBorrowRecordService.findById(record_id);


            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();

                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "common_info_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_ASSET_RECORD;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + DateUtil.getSdfYearDay() + "/" + fileName;

                                        String path = uploadPath + OssUtil.getUploadPrefix(upload_type) + DateUtil.getSdfYearDay() ;
                                        System.out.println("path: " + path);
                                        File file = new File(path);
                                        if (!file.exists() && !file.isDirectory()) {
                                            file.mkdirs();
                                        }

                                        String filePath =  path +"/" + fileName;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();


                                        ImagesFiler.imageResize(filePath,filePath);

                                        borrowRecord.setRebackImg(img_key);
                                        assetBorrowRecordService.updateById(borrowRecord);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }
    /**
     *  上传图片
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadImg")
    public JSONObject uploadImg(@RequestParam("record_id") int record_id,HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("record_id==" + record_id);

            EstateAssetCheckRecord checkRecord = assetCheckRecordService.findById(record_id);


            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();

                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "common_info_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_ASSET_RECORD;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + DateUtil.getSdfYearDay() + "/" + fileName;

                                        String path = uploadPath + OssUtil.getUploadPrefix(upload_type) + DateUtil.getSdfYearDay() ;
                                        System.out.println("path: " + path);
                                        File file = new File(path);
                                        if (!file.exists() && !file.isDirectory()) {
                                            file.mkdirs();
                                        }

                                        String filePath =  path +"/" + fileName;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();


                                        ImagesFiler.imageResize(filePath,filePath);

                                        EstateAssetCheckRecordImg recordImg = new EstateAssetCheckRecordImg();
                                        recordImg.setAssetId(checkRecord.getAssetId());
                                        recordImg.setRecordId(checkRecord.getId());
                                        recordImg.setFileType(prefix);
                                        recordImg.setImgUrl(img_key);
                                        assetCheckRecordImgService.save(recordImg);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }
}
